// var tableCount = 0;

// 添加新表格事件
$(function() {

	$("#tableColDiv2").hide();
	$("#tableRowDiv2").hide();

	$("#addNewTable").click(function() {
				var templateType = $("#tableTempType").val();
				var tableRow = $("#tableRow").val();
				var tableCol = $("#tableCol").val();
				var tableColTwo = $("#tableCol2").val();
				var tableRowTwo = $("#tableRow2").val();
				if (templateType != "") {
					var tableCount = $("#tableCount").val();
					tableCount = parseInt(tableCount) + 1;
					$("#tableCount").val(tableCount);

					jQuery.ajax({
								type : "GET",
								dataType : "json",
								async : true,
								url : "/mailreport/intemail/addnewtable",
								data : {
									"templateType" : templateType,
									"tableRow" : tableRow,
									"tableColTwo" : tableColTwo,
									"tableRowTwo": tableRowTwo,
									"tableCol" : tableCol,
									"tableCount" : tableCount
								},
								success : function(data) {
									if (data != "" && data.result == "success") {
										addTab(tableCount,data.templateValue);
										initBindGridEvent();
									} else {
										alert("error!");
									}
								}
							});
				} else {
					alert("行列参数缺失,请检查!");
				}
			});
});

//添加标签
    function addTab(tableCount,tabContent) {
      var label = "table-" + tableCount;
 		$('#tabs').tabs('add',{
				title:label,
				content:tabContent,
				closable:true
		});
    }
// 给单元格绑定事件
function initBindGridEvent() {
	$("td.editable").unbind();
	$("th.editable").unbind();
	// 添加单元格双击事件
	addGridDbClickEvent();
}

var tempButtonVal = "";

// 给单元格添加双击事件
function addGridDbClickEvent() {
	$("td.simpleInput").bind("dblclick", function() {
		var val = $(this).html().toString();

		if (val.indexOf('<a') >= 0) {
			tempButtonVal = val.substring(val.indexOf('<a'));
			val = val.substring(0, val.indexOf('<a'));
		}
		if(val.indexOf('<input') >= 0){
			return;
		}
		var width = $(this).css("width");
		var height = $(this).css("height");

		val = val.replace(/(^\s*)|(\s*$)/g, "");// trim

		$(this).html("<input type='text' onblur='saveEdit(this)' style='width:"
				+ width + ";height:" + height
				+ "; padding:0px; margin:0px;' value='" + val + "' >");
		$(this).children("input").select();
	});

	$("th.simpleInput").bind("dblclick", function() {
		var val = $(this).html().toString();

		if (val.indexOf('<a') >= 0) {
			tempButtonVal = val.substring(val.indexOf('<a'));
			val = val.substring(0, val.indexOf('<a'));
		}
		if(val.indexOf('<input') >= 0){
			return;
		}
		var width = $(this).css("width");
		var height = $(this).css("height");
		val = val.replace(/(^\s*)|(\s*$)/g, "");

		$(this).html("<input type='text' onblur='saveEdit(this)' style='width:"
				+ width + ";height:" + height
				+ "; padding:0px; margin:0px;' value='" + val + "' >");
		$(this).children("input").select();
	});
}

// 单元格失去焦点后保存表格信息
function saveEdit(gridCell) {
	$(gridCell).parent().html($(gridCell).val() + tempButtonVal);
	$(gridCell).remove();
	tempButtonVal = "";
}

// 删除行
function deleteRow(cell,type) {
	var tdRows=$(cell).parent().parent().parent().children('tr').has('td');
	if($(tdRows).length == 1){
		alert("最后一行不得删除!");
		return false;
	}
	var toDelTr=$(cell).parent().parent();
	if(type == 5 || type == 6){
		// 获取最后一个TR的格式 将其内容初始化清空 然后插入新一行
		var spanTd=$(toDelTr).children('td[rowspan]');
		var rowspan;
		if($(spanTd).length == 0){
			var spanTr=$(toDelTr).prevAll('tr:has(td[rowspan])').first();
			spanTd=$(spanTr).children('td[rowspan]');
		}else{
			var rows = parseInt($(spanTd).attr("rowspan"));
			if(rows > 1){
				alert("第一行必须最后删除！");
				return false;
			}
		}
		var rowspan = parseInt($(spanTd).attr("rowspan")) - 1;
		$(toDelTr).remove();
		$(spanTd).attr("rowspan",rowspan);
	}else
		$(toDelTr).remove();
}


// 删除列
function deleteCol(cell,type) {
	var th = $(cell).parent();
	var prevAll = $(th).prevAll(); // 之前的所有兄节点
	var thIndex = prevAll.length + 1; // 第几列下标（从1开始）

	// 获取TABLE下面的所有TR 根据下标 删除对应的TD

	var table = $(th).parent().parent();
	var allTr = $(table).children('tr');

	$.each($(allTr), function(i, obj) {
		
				$.each($(obj).children(), function(j, obj2) {
							if (type == 1 && (j + 1) == thIndex) {
								$(obj2).remove();
							}else if(type == 5) {
								var spanTd=$(obj).children('td[rowspan]');
								if($(spanTd).length == 0&& (j + 1) == thIndex)
									$(obj2).remove();
								else if($(spanTd).length != 0&& j  == thIndex)
									$(obj2).remove();
							}
				});
		});
}

function getTmplateType(cell){
	var tableCount = $(cell).closest(".portlet-content").find("#thisTableCount").val();
	var templateType = $("#templateType"+tableCount).val();
	return templateType;
}
// 删除分列,适用于模板3,4,6
function deleteCol2(cell) {
	var templateType = getTmplateType(cell);
	var th = $(cell).parent();
	var prevAll = $(th).prevAll(); // 之前的所有兄节点
	var thIndex = prevAll.length+2; // 第几列下标（从1开始）
	// 获取TABLE下面的所有TR 根据下标 删除对应的TD

	var table = $(th).parent().parent();
	var allTr = $(table).children('tr');

	$.each($(allTr), function(i, obj) {
		if (i == 0) {
			var cols=1;
			$(obj).find('th:gt(0)[colspan]').each(function(){
				var colspan=parseInt($(this).attr('colspan'));
				if(thIndex > cols && thIndex <= (cols + colspan)){
					$(this).attr('colspan',colspan-1);
					if(colspan-1 == 0)
						$(this).remove();
					return false;
				}
				cols+=colspan;
			});
		}else{
			$.each($(obj).children(), function(j, obj2) {
				if(i == 1 && (j + 2) == thIndex){
					$(obj2).remove();					
				}else if (i != 1 ){
					var spanTd=$(obj).children('td[rowspan]');
					if(templateType == 6 && $(spanTd).length != 0)
						j -= 1;	//模板六有两列行头，为了统一，将j减一。
					if((j+1) == thIndex)
						$(obj2).remove();				
				}
			});
		}
	});
}

// 删除带有分列的大列
function deleteCol3(cell) {
	var templateType = getTmplateType(cell);
	var th = $(cell).parent();
	var colspan=parseInt($(th).attr('colspan'));
	var preCols=0;
	var prevAll = $(th).prevAll('th[colspan]'); // 之前的所有兄节点
	var thIndex = prevAll.length+1;
	if(templateType == 6)	//模板六
		thIndex = prevAll.length;

	$(th).prevAll('th[colspan]').each(function(i,th){
		if(i< (thIndex -1)){	//prev向前遍历，第一列表头不算
			var span=parseInt($(this).attr('colspan'));
			preCols+=span;
		}
	});

	// 获取TABLE下面的所有TR 根据下标 删除对应的TD
	var table = $(th).parent().parent();
	var allTr = $(table).children('tr');
	$.each($(allTr), function(i, obj) {
				if (i == 0) {
					$.each($(obj).children('th'), function(j, obj2) {
						if(j == thIndex)
							$(obj2).remove();
					});
				}else {
					$.each($(obj).children(), function(j, obj2) {
						if(i == 1 && j >= preCols && j < (preCols+colspan))
							$(obj2).remove();
						else if (i != 1){
							var spanTd=$(obj).children('td[rowspan]');
							if(templateType == 6 && $(spanTd).length != 0)
								j -= 1;	//模板六有两列行头，为了统一，将j减一。
							if(j > preCols && j <= (preCols+colspan)) 
								$(obj2).remove();
						} 
					});
				}
			});
}

// 新增行
function addNewRow(cell, type) {
	var thisTableCount = $(cell).parent().find("[id='thisTableCount']");// 该表格的count数

	var table1 = $(cell).parent().children('table');
	var tableIn = $(table1).find("[id='emailContentTable']");

	// 获取最后一个TR的格式 将其内容初始化清空 然后插入新一行
	var lastTr = $(tableIn).children('tbody').children('tr').last();
	var lastSpanTr= $(tableIn).children('tbody').children('tr:has(td[rowspan])').last();
	var spanTd=$(lastSpanTr).children('td[rowspan]');
	var rowspan = parseInt($(spanTd).attr("rowspan")) + 1;
	$(spanTd).attr("rowspan",rowspan);
	
	var rowTitleName = "";// 行抬头
	if (type == 1) {// 汇总模板
		rowTitleName = "新类别";
	} else if (type == 2) { // 详细指标模板
		rowTitleName = "新指标";
	} else {
		rowTitleName = "新指标";
	}

	var rowValue = ""; // 新增行的内容
	var allTd = $(lastTr).children('td');

	$.each($(allTd), function(i, obj) {
		 if(typeof($(obj).attr("rowspan"))!="undefined" && i == 0){
				 	return true;
		 }
		var classList = $(obj).attr('class');
		if (classList == 'td1 editable simpleInput') { // 行头
			rowValue = rowValue
					+ "<td id='templateTd"
					+ $(thisTableCount).val()
					+ "' name='templateTd"
					+ $(thisTableCount).val()
					+ "' class='td1 editable simpleInput' style='color:red'>"
					+ rowTitleName
					+ "<a style='color:#6C6C6C' href='javascript:void(0)' onclick='deleteRow(this,"+type+")'>删除</a></td>";
		} else if (classList == 'editable simpleInput') { // 可编辑内容
			rowValue = rowValue
					+ "<td id='templateTd"
					+ $(thisTableCount).val()
					+ "' name='templateTd"
					+ $(thisTableCount).val()
					+ "' class='editable simpleInput' style='color:red'>"
//					if(type !=5)
//						rowValue = rowValue +"可编辑"
					rowValue = rowValue +"</td>";
		} else if (classList == undefined) { // 其他
			rowValue = rowValue + "<td id='templateTd"
					+ $(thisTableCount).val() + "' name='templateTd"
					+ $(thisTableCount).val() + "'></td>";
		}
	});
	$newRow = $("<tr onMouseOver=\"this.className='tdbg10'\" onMouseOut=\"this.className='tdbg11'\" class='tdbg11'>"
			+ rowValue + "</tr>");
	$(tableIn).children('tbody').append($newRow);
	initBindGridEvent(); // 初始化绑定事件
}

// 新增带有分行的行
function addNewRow2(cell,type){
	var thisTableCount = $(cell).parent().find("[id='thisTableCount']");// 该表格的count数
	var templateType = $("#templateType" + $(thisTableCount).val()).val();
	var spanNum= $(cell).parent().find("[id='spanNum']").val();
	var table1 = $(cell).parent().children('table');
	var tableIn = $(table1).find("[id='emailContentTable']");
	
	var lastTr = $(tableIn).children('tbody').children('tr').last();
	var allTd = $(lastTr).children('td');
	var rowValue = "<td rowspan='1' id='templateTd"   // 新增行的行头
					+ $(thisTableCount).val()
					+ "' name='templateTd"
					+ $(thisTableCount).val()
					+ "' class='td1 editable simpleInput' style='color:red'>新类别</td>";
	$.each($(allTd), function(i, obj) {
		 if(typeof($(obj).attr("rowspan"))!="undefined" && i == 0){
				 	return true;
		 }
		var classList = $(obj).attr('class');
		if (classList == 'td1 editable simpleInput') { // 行头
			rowValue = rowValue
					+ "<td id='templateTd"
					+ $(thisTableCount).val()
					+ "' name='templateTd"
					+ $(thisTableCount).val()
					+ "' class='td1 editable simpleInput' style='color:red'>新指标"
					+ "<a style='color:#6C6C6C' href='javascript:void(0)' onclick='deleteRow(this,"+type+")' >删除</a></td>";
		} else if (classList == 'editable simpleInput') { // 可编辑内容
			rowValue = rowValue
					+ "<td id='templateTd"
					+ $(thisTableCount).val()
					+ "' name='templateTd"
					+ $(thisTableCount).val()
					+ "' class='editable simpleInput' style='color:red'>"
//					if(type !=5)
//						rowValue = rowValue +"可编辑"
					rowValue = rowValue +"</td>";
		} else if (classList == undefined) { // 其他
			rowValue = rowValue + "<td id='templateTd"
					+ $(thisTableCount).val() + "' name='templateTd"
					+ $(thisTableCount).val() + "'></td>";
		}
	});
	$newRow = $("<tr onMouseOver=\"this.className='tdbg10'\" onMouseOut=\"this.className='tdbg11'\" class='tdbg11'>"
			+ rowValue + "</tr>");
	$(tableIn).children('tbody').append($newRow);
	initBindGridEvent(); // 初始化绑定事件
}

//新增注释行
function addComment(cell, type) {
	var thisTableCount = $(cell).parent().find("[id='thisTableCount']");// 该表格的count数
	var table1 = $(cell).parent().children('table');
	// 获取最后一个TR的格式  然后插入新一行
	var lastTr = $(table1).children('tbody').children('tr').last();
	if(lastTr.find("td[name='tableComment']").length > 0){
		alert("注释行已经存在！");
		return;
	}
	var rowValue = "<td id='tableComment' name='tableComment"
			+ "' class='td1 editable simpleInput' style='color:red'>注释：可编辑"
			+ "<a style='color:#6C6C6C' href='javascript:void(0)' onclick='delComment(this)' >删除</a></td>";
	var newRow = "<tr onMouseOver=\"this.className='tdbg10'\" onMouseOut=\"this.className='tdbg11'\" class='tdbg11'>"
			+ rowValue + "</tr>";
	$(lastTr).after(newRow);
	initBindGridEvent(); // 初始化绑定事件
}

function delComment(cell){
	$(cell).closest('tr').remove();
}

// 新增列
function addNewCol(cell) {
	var thisTableCount = $(cell).parent().find("[id='thisTableCount']");// 该表格的count数
	var templateType = $("#templateType" + $(thisTableCount).val()).val();
	var spanNum= $(cell).parent().find("[id='spanNum']").val();
	var table1 = $(cell).parent().children('table');
	var tableIn = $(table1).find("[id='emailContentTable']");

	// 超过20列就不允许再添加
	var lastTr = $(tableIn).children('tbody').children('tr').last();
	var nowCols = $(lastTr).children('td').length;
	if ((nowCols + 3) > 40) {
		alert("表格最多只能有40列！");
		return false;
	}

	// 在所有TR里都加上三列 表头 = 新指标/日比/周比 及内容
	var allTr = $(tableIn).children('tbody').children('tr');
	$.each($(allTr), function(i, obj) {

		var colsValue = "";
		if (i == 0) { // 表头
			colsValue = "<th id='templateTh"
					+ $(thisTableCount).val()
					+ "' name='templateTh"
					+ $(thisTableCount).val()
					+ "' class='editable simpleInput' style='color:red'>新指标 &nbsp;<a style='color:#6C6C6C' href='javascript:void(0)' onclick='deleteCol(this,"
					+templateType+","+spanNum
					+")' >删除</a></th><th id='templateTh"
					+ $(thisTableCount).val()
					+ "' name='templateTh"
					+ $(thisTableCount).val()
					+ "'>日比 <a style='color:#6C6C6C' href='javascript:void(0)' onclick='deleteCol(this,"
					+templateType+","+spanNum
					+")' >删除</a></th><th id='templateTh"
					+ $(thisTableCount).val()
					+ "' name='templateTh"
					+ $(thisTableCount).val()
					+ "'>周比 <a style='color:#6C6C6C' href='javascript:void(0)' onclick='deleteCol(this,"
					+templateType+","+spanNum
					+")' >删除</a></th>";
		} else {
			colsValue = "<td id='templateTd"
					+ $(thisTableCount).val()
					+ "' name='templateTd"
					+ $(thisTableCount).val()
					+ "'class='editable simpleInput' style='color:red'></td><td id='templateTd"
					+ $(thisTableCount).val() + "' name='templateTd"
					+ $(thisTableCount).val() + "'></td><td id='templateTd"
					+ $(thisTableCount).val() + "' name='templateTd"
					+ $(thisTableCount).val() + "'></td>";
		}
		$newColTitile = $(colsValue);
		$(obj).append($newColTitile);
	});
	initBindGridEvent(); // 初始化绑定事件
}

// 新增分列
function addNewCol2(cell) {
	var thisTableCount = $(cell).parent().find("[id='thisTableCount']");// 该表格的count数
	var table1 = $(cell).parent().children('table');
	var tableIn = $(table1).find("[id='emailContentTable']");

	// 超过40列就不允许再添加
	var lastTr = $(tableIn).children('tbody').children('tr').last();
	var nowCols = $(lastTr).children('td').length;
	if (nowCols > 40) {
		alert("分列最多只能有40列！");
		return false;
	}

	// 在所有TR里都加上三列 表头 = 新指标/日比/周比 及内容
	var allTr = $(tableIn).children('tbody').children('tr');
	$.each($(allTr), function(i, obj) {

		var colsValue = "";
		var j;
		if (i == 0){
			var colspan=$(tableIn).find('th[colspan]').last().attr('colspan');
			if(typeof(colspan) == "undefined"){//列表头已经被删完了，只剩下第一格,要加一格表头
				colsValue = colsValue
						+ "<th colspan='1' id='templateTh"
						+ $(thisTableCount).val()
						+ "' name='templateTh"
						+ $(thisTableCount).val()
						+ "' class='editable simpleInput' style='color:red'>新类别</th>";
			}else{
				colspan = 1 + parseInt(colspan);
				$(tableIn).find('th[colspan]').last().attr('colspan', colspan);
				return;
			}
		}
		else if (i == 1) {
				colsValue = colsValue
						+ "<th id='templateTh"
						+ $(thisTableCount).val()
						+ "' name='templateTh"
						+ $(thisTableCount).val()
						+ "' class='editable simpleInput' style='color:red'>新指标&nbsp;<a style='color:#6C6C6C' href='javascript:void(0)'  onclick='deleteCol2(this)' >删除</a></th>";
		} else {
				colsValue = colsValue
						+ "<td id='templateTd"
						+ $(thisTableCount).val()
						+ "' name='templateTd"
						+ $(thisTableCount).val()
						+ "'class='editable simpleInput' style='color:red'></td>";
		}
		$newColTitile = $(colsValue);
		$(obj).append($newColTitile);
	});
	initBindGridEvent(); // 初始化绑定事件
}

// 新增带有分列的大列
function addNewCol3(cell) {
	var thisTableCount = $(cell).parent().find("[id='thisTableCount']");// 该表格的count数
	var table1 = $(cell).parent().children('table');
	var tableIn = $(table1).find("[id='emailContentTable']");

	// 超过20列就不允许再添加
	var lastTr = $(tableIn).children('tbody').children('tr').last();
	var nowCols = $(lastTr).children('td').length;
	if (nowCols> 40) {
		alert("表格最多只能有40列！");
		return false;
	}

	// 在所有TR里都加上三列 表头 = 新指标/日比/周比 及内容
	var allTr = $(tableIn).children('tbody').children('tr');
	$.each($(allTr), function(i, obj) {

		var colsValue = "";
		if (i == 0) { // 表头
			colsValue = "<th id='templateTh"
					+ $(thisTableCount).val()
					+ "'  colspan='1'  name='templateTh"
					+ $(thisTableCount).val()
					+ "' class='editable simpleInput' style='color:red'>新类别 &nbsp;<a style='color:#6C6C6C' href='javascript:void(0)' onclick='deleteCol3(this)' >删除</a></th>"
		} else if(i==1){
			colsValue = colsValue+ "<th id='templateTh"
						+ $(thisTableCount).val()
						+ "' name='templateTh"
						+ $(thisTableCount).val()
						+ "' class='editable simpleInput' style='color:red'>新分量&nbsp;<a style='color:#6C6C6C' href='javascript:void(0)'  onclick='deleteCol2(this)' >删除</a></th>";
		}else{
			colsValue = "<td id='templateTd"
					+ $(thisTableCount).val()
					+ "' name='templateTd"
					+ $(thisTableCount).val()
					+ "'class='editable simpleInput' style='color:red'></td>";
		}
		$newColTitile = $(colsValue);
		$(obj).append($newColTitile);
	});
	initBindGridEvent(); // 初始化绑定事件
}


// 全表格删除
function dropThisTable(cell) {
	$(cell).parent().remove();
	// var tableCount = $("#tableCount").val();
	// tableCount = parseInt(tableCount) - 1;
	// $("#tableCount").val(tableCount);
}

// 新增数据源sql
function addNewSql(cell) {
	var thisTableCount = $(cell).parent().parent()
			.find("[id='thisTableCount']");// 该表格的count数
	var dbtemplate = $("#dbTemplate").val();
	dbtemplate = dbtemplate.replace(/\#tableCount/g, $(thisTableCount).val())
	$newSql = dbtemplate;
	// $newSql = $("<div></br>新指标集: <input type='button' style='float:right'
	// class='btn btn-primary btn-xs' onclick='dropThisSql(this)'
	// value='删除该数据源配置'/><input style='width:50%'type='text' id='templateIndex"
	// + $(thisTableCount).val() + "' name='templateIndex" +
	// $(thisTableCount).val() + "' class='form-control'/></input>SQL:<textarea
	// style='width:100%;height:60px' id='templateSql" + $(thisTableCount).val()
	// + "' name='templateSql" + $(thisTableCount).val() +
	// "'></textarea></div>");
	$(cell).before($newSql);
}

// 该数据源配置删除
function dropThisSql(cell) {
	$(cell).closest('#sqlconf').remove();
}

// 发送频率选择
function sendFre(val) {
	$("#sendFreValue").val(val);
	$(':input[alias="freValue"]').val("");
	if(val == 'day' || val == 'week')
		$(':input[alias="freValue"]').attr('readonly',true);
	else 
		$(':input[alias="freValue"]').attr('readonly',false);
}

// 表单提交校验
function subCheck() {
	return true;
}

// 模板选择change
function templateChange() {
	var type = $("#tableTempType").val();

	$("#tableRow").val("");
	$("#tableCol").val("");
	$("#tableCol2").val("");
	$("#tableRow2").val("");
	if (type == 1) {
		$("#tableRowDiv").show();
		$("#tableX").show();
		$("#tableColDiv").show();
		$("#tableColDiv2").hide();
		$("#tableRowDiv2").hide();
	} else if (type == 2) {
		$("#tableRowDiv").show();
		$("#tableX").hide();
		$("#tableColDiv").hide();
		$("#tableColDiv2").hide();
		$("#tableRowDiv2").hide();
	} else if(type == 3){
		$("#tableRowDiv").hide();
		$("#tableX").hide();
		$("#tableColDiv").hide();
		$("#tableColDiv2").show();
		$("#tableRowDiv2").hide();
	} else{
		$("#tableRowDiv").show();
		$("#tableX").show();
		$("#tableColDiv").show();
		$("#tableColDiv2").show();
		if(type == 6)
			$("#tableRowDiv2").show();
		else
			$("#tableRowDiv2").hide();
	}
}

// 获取模板5表格的单元格内容
function getTableTh5(emailContentTable, i) {
	var rowspan=$(emailContentTable).prev('#spanNum').val();
//	alert("rowspan: "+rowspan);
	rowspan=parseInt(rowspan);
	// 获取第一个TR的格式
	var firstTr = $(emailContentTable).find('tr').first();
	// 第一行th内容
	var allTh = $(firstTr).find('th');
	var firstTh = "th" + i + ":";
	var secondTh = "";
	$.each($(allTh), function(i, obj) {
				var thValue = $(obj).html();
				if (thValue.indexOf("<a") >= 0) {
					thValue = thValue.substring(0, thValue.indexOf("<a")).trim();
				}
				thValue = thValue.replace(/\&nbsp;/g, "").replace(/(^\s*)|(\s*$)/g, "");
				if (thValue == "") {
					thValue = "null";
				}
				firstTh = firstTh + thValue + ",";
	});
	// td内容
	var allTr = $(emailContentTable).find('tr:gt(0)');
	var tdValus = "td" + i + ":";

	$.each($(allTr), function(i, obj) {
			var allTd = $(obj).children('td'); //当前行的td
			var firstTd;
			$.each($(allTd), function(j, obj2){
				if(j == 0)
					firstTd=obj2;
				var tdValue = $(obj2).html();
				if (tdValue.indexOf("<a") >= 0) {
					tdValue = tdValue.substring(0, tdValue.indexOf("<a"));
				}
				tdValue = tdValue.replace(/\&nbsp;/g, "").replace(/(^\s*)|(\s*$)/g, "");
				if (tdValue == "") {
					tdValue = "null";
				}
				tdValus = tdValus + tdValue +",";
//				if(i < rowspan){
//					 if((i == 0 && j == 1) || (i > 0 && j==0))
//						secondTh+=tdValue+",";
//				}
				 if(typeof($(firstTd).attr("rowspan")) != "undefined" && j == 1){
				 	if(i > 0)
				 		secondTh += "\n"
				 	secondTh += tdValue+",";
				 }else if(typeof($(firstTd).attr("rowspan")) == "undefined" && j == 0)
				 	secondTh += tdValue+",";
			});
			tdValus = tdValus + "\n"; //一行结束插入"\n"符号
	});
	return firstTh + "~"+secondTh+"~" + tdValus;
}

// 获取模板6表格的单元格内容
function getTableTh6(emailContentTable, i) {
	// 获取第一个TR的格式
	var firstTr = $(emailContentTable).find('tr').first();
	// 第一行th内容
	var allTh = $(firstTr).find('th');
	var firstTh = "th" + i + ":";
	var secondColTh = "";	//分列头
	var secondRowTh = "";	//分行头
	var cols=0;
	$.each($(allTh), function(i, obj) {
				var thValue = $(obj).html();
				if (thValue.indexOf("<a") >= 0) {
					thValue = thValue.substring(0, thValue.indexOf("<a")).trim();
				}
				thValue = thValue.replace(/\&nbsp;/g, "").replace(/(^\s*)|(\s*$)/g, "");
				if (thValue == "") {
					thValue = "null";
				}
				firstTh = firstTh + thValue + ",";
				if(i != 0){  //找到对应的第二行的分列标
					var secondTrTh = $(firstTr).next().find('th');
					var colspan=parseInt($(obj).attr('colspan'));  //分列数
					$.each($(secondTrTh), function(j, obj2) {
						if(j >= cols && j < (cols + colspan)){  //对应的第二行的分列
							var thTwoValue = $(obj2).html();
							if (thTwoValue.indexOf("<a") >= 0) {
								thTwoValue = thTwoValue.substring(0,
										thTwoValue.indexOf("<a"));
							}
							thTwoValue = thTwoValue.replace(/\&nbsp;/g, "").replace(
									/(^\s*)|(\s*$)/g, "");
							if (thTwoValue == "") {
								thTwoValue = "null";
							}

							secondColTh = secondColTh + thTwoValue + ",";
						}
						if(j == (cols + colspan-1)){
							secondColTh = secondColTh + "\n"; //分列之间用",\n"间隔开
							return false;
						}
					});
					cols+=colspan;
				}
	});
	// td内容
	var allTr = $(emailContentTable).find('tr:gt(1)');
	var tdValus = "td" + i + ":";
	$.each($(allTr), function(i, obj) {
			var allTd = $(obj).children('td'); //当前行的td
			var firstTd;
			$.each($(allTd), function(j, obj2){
				if(j == 0)
					firstTd=obj2;
				var tdValue = $(obj2).html();
				if (tdValue.indexOf("<a") >= 0) {
					tdValue = tdValue.substring(0, tdValue.indexOf("<a"));
				}
				tdValue = tdValue.replace(/\&nbsp;/g, "").replace(/(^\s*)|(\s*$)/g, "");
				if (tdValue == "") {
					tdValue = "null";
				}
				tdValus = tdValus + tdValue +",";
				if(typeof($(firstTd).attr("rowspan")) != "undefined" && j == 1){
				 	if(i > 0)
				 		secondRowTh += "\n"
				 	secondRowTh += tdValue+",";
				 }else if(typeof($(firstTd).attr("rowspan")) == "undefined" && j == 0)
				 	secondRowTh += tdValue+",";
			});
			tdValus = tdValus + "\n"; //一行结束插入"\n"符号
	});
	return firstTh + "~"+secondColTh+"!!"+secondRowTh+"~" + tdValus;
}


// 获取模板3,4表格的单元格内容
function getTableTh2(emailContentTable, i) {
	// 获取第一个TR的格式
	var firstTr = $(emailContentTable).find('tr').first();
	// 第一行th内容
	var allTh = $(firstTr).find('th');
	// 第二行th内容
	var secondRowTh = $(firstTr).next().find('th');
	var firstTh = "th" + i + ":";
	var secondTh = "";
	var cols=0;
	$.each($(allTh), function(i, obj) {
				var thValue = $(obj).html();
				if (thValue.indexOf("<a") >= 0) {
					thValue = thValue.substring(0, thValue.indexOf("<a"));
				}
				thValue = thValue.replace(/\&nbsp;/g, "").replace(/(^\s*)|(\s*$)/g, "");
				if (thValue == "") {
					thValue = "null";
				}
				firstTh = firstTh + thValue + ",";
				
				if(i !=0){  //找到对应的第二行的分列标
					var colspan=parseInt($(obj).attr('colspan'));  //分列数
					$.each($(secondRowTh), function(j, obj2) {
						if(j >= cols && j < (cols + colspan)){  //对应的第二行的分列
							var thTwoValue = $(obj2).html();
							if (thTwoValue.indexOf("<a") >= 0) {
								thTwoValue = thTwoValue.substring(0,
										thTwoValue.indexOf("<a"));
							}
							thTwoValue = thTwoValue.replace(/\&nbsp;/g, "").replace(
									/(^\s*)|(\s*$)/g, "");
							if (thTwoValue == "") {
								thTwoValue = "null";
							}

							secondTh = secondTh + thTwoValue + ",";
						}
						if(j == (cols + colspan-1)){
							secondTh = secondTh + "\n"; //分列之间用",\n"间隔开
							return false;
						}
					});
					cols+=colspan;
				}
			});
	
	// td内容，从第3行开始
	var allTr = $(emailContentTable).find('tr:gt(1)');
	
	var tdValus = "td" + i + ":";
	$.each($(allTr), function(i, obj) {
			var allTd = $(obj).children('td'); //当前行的td
			var firstTd;
			$.each($(allTd), function(j, obj2){
				var tdValue = $(obj2).html();
				if (tdValue.indexOf("<a") >= 0) {
					tdValue = tdValue.substring(0, tdValue.indexOf("<a"));
				}
				tdValue = tdValue.replace(/\&nbsp;/g, "").replace(/(^\s*)|(\s*$)/g, "");
				if (tdValue == "") {
					tdValue = "null";
				}
				tdValus = tdValus + tdValue + ",";
			});
			tdValus = tdValus + "\n"; //一行td结束插入一个\n
	});
	return firstTh + "~" + secondTh + "~" + tdValus;
}

// 获取模板1,2表格的单元格内容
function getTableTh1(emailContentTable, i) {
	var allTh = $(emailContentTable).find('th');
	var firstTh = "th" + i + ":";
	var secondTh = "";
	var tdValus = "td" + i + ":";
	$.each($(allTh), function(i, obj) {
		var thValue = $(obj).html();
		if (thValue.indexOf("<a") >= 0) {
			thValue = thValue.substring(0,
			thValue.indexOf("<a"));
		}
		thValue = thValue.replace(/\&nbsp;/g, "").replace(/(^\s*)|(\s*$)/g, "");
		if (thValue == "") {
			thValue = "null";
		}
		firstTh = firstTh + thValue + ",";
	});
	secondTh = secondTh + "null,";
	// td内容
	var allTr = $(emailContentTable).find('tr:gt(0)');
	$.each($(allTr), function(i, objtr) {
		var allTd = $(objtr).children('td'); //当前行的td
		$.each($(allTd), function(i, obj) {
			var tdValue = $(obj).html();
			if (tdValue.indexOf("<a") >= 0) {
				tdValue = tdValue.substring(0,tdValue.indexOf("<a"));
			}
			tdValue = tdValue.replace(/\&nbsp;/g, "").replace(/(^\s*)|(\s*$)/g, "");
			if (tdValue == "") {
				tdValue = "null";
			}
			tdValus = tdValus + tdValue + ",";
		});							
		tdValus = tdValus  + "\n";
	});
	return firstTh + "~" + secondTh + "~" + tdValus;
}

function getComment(div){
	var tableComment =  $(div).find("[id='tableComment']");
	if(tableComment.length == 0)
		return '';
	else {
		var commVal = tableComment.html();
		if (commVal.indexOf("<a") >= 0) {
			commVal = commVal.substring(0, commVal.indexOf("<a"));
		}		
		return commVal.replace(/(^\s*)|(\s*$)/g, "");
	
	}
}

//检查邮件基本信息是否为空
function checkParam(){
	var canSub=true;
	$(":input[title]").each(function() {
		var value = $(this).val();
		if(value == null||value.replace(/(^\s*)|(\s*$)/g, "") == ""){
			var title = $(this).attr('title');
			canSub=false;
			alert(title+"不能为空");
			return false;
		}
	});
	return canSub;
}
//检查发送频率是否正确
function checkSendFre(){
	var fre=$("#sendFreValue").val();
	if(fre　==　'day' ||　fre　==　'week')
		return true;
	var sendFre=$(':input[alias="freValue"]').val();
	if(sendFre==null || sendFre.replace(/(^\s*)|(\s*$)/g, "") == ""){
		alert('发送频率不能为空！');
		return false;
	}
	var days=sendFre.split(";");
	for (day in days){
		var weekday=parseInt(day);
		if(isNaN(weekday) || weekday < 1 || weekday > 7){
			alert('发送频率不正确！');
			return false;
		}
	}
	return true;	
}
//检查报警电话是否正确
function checkWarnTel(){
	var tel=$(":input[title='预警短信']").val().replace(/(^\s*)|(\s*$)/g, "");
	var flag=true;
	var tels = tel.split(";");
	 $.each(tels,function(n,value){ 
	 	var warnTel = parseInt(value);
	 	if(value.length != 11 || isNaN(warnTel)){
			alert('预警短信格式错误！');
			flag = false;
			return false;
		}
      });  
	return flag;
}

//检查阈值是否正确
function checkThreshold(){
	var threshold1=$(":input[title='阈值1']").val().replace(/(^\s*)|(\s*$)/g, "");
	var threshold2=$(":input[title='阈值2']").val().replace(/(^\s*)|(\s*$)/g, "");
	threshold1 = parseFloat(threshold1);
	threshold2 = parseFloat(threshold2);
	if(isNaN(threshold1) || isNaN(threshold2)){
		alert('阈值格式错误！');
		return false;
	}
	
	if((threshold1 > 1 || threshold1 < 0) || (threshold2 > 1 || threshold2 < 0)){
		alert('阈值大小必须在[0-1]之间！');
		return false;
	}
	return true;
}

function transfer(str){
	return str.replace(/\?/g,"%3F").replace(/\&amp;/g,"%26").replace(/&/g,"%26").replace(/=/g,"%3D").replace(/\+/g,'%2B');
}

// 添加新邮件
$(function() {
			$("#addNewEmail").click(function() {
				if(checkParam() == false)
					return false;
				if(checkSendFre() == false)
					return false;
				if(checkWarnTel() == false)
					return false;
				if(checkThreshold() == false)
					return false;
				
				var templateThs = "";
				var templateTwoThs = "";
				var templateTds = "";
				var tableNameValus = "";
				var tableComments = "";

				var tableCount = $("#tableCount").val();

				for (var i = 1; i <= tableCount; i++) {
					var templateType = $("#templateType" + i);
					if ($(templateType).val() == undefined) {
						continue;
					}
					var div = $(templateType).parent();
					var emailContentTable = $(div)
							.find("[id='emailContentTable']");
					// th内容
					var rows;
					if ($(templateType).val() == 1 || $(templateType).val() == 2) {
						rows = getTableTh1(emailContentTable, i).split("~");
					} else if($(templateType).val() == 5 ){
						rows = getTableTh5(emailContentTable, i).split("~");
					}else if($(templateType).val() == 6 ){
						rows = getTableTh6(emailContentTable, i).split("~");
					}else{
						rows = getTableTh2(emailContentTable, i).split("~");
//						alert(templateThs+"~"+templateTwoThs+"~"+templateTds);
					}
					templateThs = templateThs + rows[0] + ";";
					templateTwoThs = templateTwoThs + rows[1] + ";";
					templateTds = templateTds + rows[2] + ";";
					// tableName
					var tableName = $(div).find("[id='tableName']").html().replace(/\&nbsp;/g, "").replace(/(^\s*)|(\s*$)/g, "");;
					var commentVal = "tableComment" + i + ":" + getComment(div);
					tableName = "tableName" + i + ":" + tableName;
					tableNameValus = tableNameValus + tableName + ";@";
					tableComments = tableComments + commentVal+ ";@";
				}

				if (templateThs != "" && templateTds != ""
						&& tableNameValus != "") {
					var contentSerialize = $('#setEmailContent').serialize();
					var subValue = contentSerialize + "&templateThs="
							+ transfer(templateThs) + "&templateTwoThs=" + transfer(templateTwoThs)
							+ "&templateTds=" + transfer(templateTds) + "&tableNames="
							+ transfer(tableNameValus)+"&tableComments="+transfer(tableComments);
//encodeURIComponent(tableComments)
					jQuery.ajax({
								type : "post",
								async : true,
								url : "/mailreport/intemail/addNewEmail",
								data : subValue,
								success : function(data) {
									if (data == "success") {
										alert("添加成功！");
										window.location.href="/mailreport/intemail/manager/show";
									} else if (data == "error") {
										alert("添加失败!");
//										window.location.href="/intemail/manager/show";
									} else {
										alert(data);
									}
								}
							});
				} else {
					alert("参数缺失,请检查!");
				}
			});
		});

// 更新邮件
$(function() {
	$("#updateEmail").click(function() {
				if(checkParam() == false)
					return false;
				if(checkSendFre() == false)
					return false;
				if(checkWarnTel() == false)
					return false;
				if(checkThreshold() == false)
					return false;
				var templateThs = "";
				var templateTwoThs = "";
				var templateTds = "";
				var tableNameValus = "";
				var tableComments = "";
				var tableCount = $("#tableCount").val();

				for (var i = 1; i <= tableCount; i++) {
					var templateType = $("#templateType" + i);

					if ($(templateType).val() == undefined) {
						continue;
					}

					var div = $(templateType).parent();
					var emailContentTable = $(div)
							.find("[id='emailContentTable']");
					// th内容
					if ($(templateType).val() == 1 || $(templateType).val() == 2) {
						rows = getTableTh1(emailContentTable, i).split("~");
					} else if($(templateType).val() == 5 ){
						rows = getTableTh5(emailContentTable, i).split("~");
					}else if($(templateType).val() == 6 ){
						rows = getTableTh6(emailContentTable, i).split("~");
					}else{
						rows = getTableTh2(emailContentTable, i).split("~");
					}
//						alert(templateThs+"~"+templateTwoThs+"~"+templateTds);
					templateThs = templateThs + rows[0] + ";";
					templateTwoThs = templateTwoThs + rows[1] + ";";
					templateTds = templateTds + rows[2] + ";";

					// tableName
					var tableName = $(div).find("[id='tableName']").html().replace(/\&nbsp;/g, "").replace(/(^\s*)|(\s*$)/g, "");;
					var commentVal = "tableComment" + i + ":" + getComment(div);
					tableName = "tableName" + i + ":" + tableName;
					tableNameValus = tableNameValus + tableName + ";@";
					tableComments = tableComments + commentVal+ ";@";
				}
		if (templateThs != "" && templateTds != "" && tableNameValus != "") {
			var contentSerialize = $('#setEmailContent').serialize();
			var subValue = contentSerialize + "&templateThs="
							+ transfer(templateThs) + "&templateTwoThs=" + transfer(templateTwoThs)
							+ "&templateTds=" + transfer(templateTds) + "&tableNames="
							+ transfer(tableNameValus)+"&tableComments="+transfer(tableComments);

			jQuery.ajax({
						type : "post",
						async : true,
						url : "/mailreport/intemail/addNewEmail",
						data : subValue,
						success : function(data) {
							if (data == "success") {
								alert("更新成功！");
								window.location.href="/mailreport/intemail/manager/show";
							} else if(data == "error"){
								alert("更新失败!");
//								window.location.href="/intemail/manager/show";
							}else{
								alert(data);
							}
						}
					});
		} else {
			alert("参数缺失,请检查!");
		}
	});
});